package org.example.controller;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.example.service.LoanDataExcelImportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 贷款数据Excel导入控制器
 * 支持用户基本信息和还款计划的分表导入
 */
@Slf4j
@RestController
@RequestMapping("/api/loan-data")
public class LoanDataExcelImportController {

    @Autowired
    private LoanDataExcelImportService loanDataExcelImportService;

    /**
     * 导入Excel文件
     * @param file Excel文件
     * @return 导入结果
     */
    @PostMapping("/import-excel")
    public ResponseEntity<Map<String, Object>> importExcel(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 文件验证
            if (file == null || file.isEmpty()) {
                result.put("success", false);
                result.put("message", "请选择要上传的Excel文件");
                return ResponseEntity.badRequest().body(result);
            }

            // 检查文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || (!originalFilename.endsWith(".xlsx") && !originalFilename.endsWith(".xls"))) {
                result.put("success", false);
                result.put("message", "请上传Excel文件(.xlsx或.xls格式)");
                return ResponseEntity.badRequest().body(result);
            }

            // 检查文件大小 (限制为10MB)
//            if (file.getSize() > 10 * 1024 * 1024) {
//                result.put("success", false);
//                result.put("message", "文件大小不能超过10MB");
//                return ResponseEntity.badRequest().body(result);
//            }

            log.info("开始导入Excel文件: {}, 大小: {} bytes", originalFilename, file.getSize());

            // 执行导入
            LoanDataExcelImportService.ImportResult importResult = loanDataExcelImportService.importExcel(file);

            result.put("success", importResult.isSuccess());
            result.put("message", importResult.getMessage());
            result.put("errorMessages", importResult.getErrorMessages());

            log.info("Excel导入完成: {}", JSON.toJSONString(result));

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("导入Excel文件异常", e);
            result.put("success", false);
            result.put("message", "导入失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取Excel模板下载链接
     * @return 模板信息
     */
    @GetMapping("/template")
    public ResponseEntity<Map<String, Object>> getTemplate() {
        Map<String, Object> result = new HashMap<>();
        
        // Excel模板列信息
        String[] headers = {
            "下单订单号", "user_id", "放款时间", "放款金额", "期数", "到期时间", 
            "实还时间", "还款状态", "逾期天数", "应收本金", "收货地址省", 
            "收货地址市", "收货地址区", "性别", "生日", "月收入", "学历", 
            "婚姻状况", "sesame_score"
        };

        String[] descriptions = {
            "必填，唯一标识", "必填，用户ID", "必填，格式：yyyy-MM-dd HH:mm:ss", 
            "必填，金额>0", "必填，期数>0", "必填，格式：yyyy-MM-dd HH:mm:ss",
            "可选，格式：yyyy-MM-dd HH:mm:ss", "必填，1=在途，2=正常还款，3=逾期还款",
            "可选，逾期天数>=0", "必填，金额>=0", "可选，省份名称",
            "可选，城市名称", "可选，区县名称", "可选，0=女，1=男",
            "可选，格式：yyyy-MM-dd", "可选，金额>=0", "可选，学历信息",
            "可选，婚姻状况", "可选，芝麻信用分"
        };

        result.put("success", true);
        result.put("headers", headers);
        result.put("descriptions", descriptions);
        result.put("message", "请按照模板格式准备Excel文件，必填字段不能为空。系统会自动去重：相同订单号的用户信息只保存一次，相同订单号和期数的还款计划只保存一次。");

        return ResponseEntity.ok(result);
    }

    /**
     * 健康检查接口
     * @return 服务状态
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "贷款数据Excel导入服务运行正常");
        result.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(result);
    }
}
